package com.csw.android.androidtest.module.storage;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.csw.android.androidtest.app.MyApplication;
import com.csw.android.androidtest.entities.Student;
import com.csw.android.androidtest.ui.LogViewFragment;
import com.csw.android.dev_utils.utils.ToastUtils;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 数据库存储，也是基于文件存储，android提供的sqlite是关系型数据库，表与表之间可以通过外键关联，通过关联关系
 * 查询数据。
 * <p>
 * 这个还是比较麻烦的，要写sql语句，还有数据库版本更新处理，为了数据库更新后数据继承，肯定不能简单粗暴的删除重
 * 新建表，建议使用第三方sdk，如greenDao，对数据库的操作会方便很多，也有第三方sdk提供了greenDao数据库更新处理。
 * <p>
 * 优势在于当存在大量表单数据需要存储，并且需要根据表单的某项数据进行过滤查询时，使用数据库很有优势。若是用文件
 * 或者SP键值对存储，则需要将整个表单加载到内存，然后再进行遍历，性能比不上数据库的
 */
public class DatabaseTest extends LogViewFragment {

    @Override
    public void initData() {
        super.initData();
        Student student = new Student("蔡树伟", "男", 28);

        saveStudent(student);
    }

    private void saveStudent(Student student) {
        Disposable disposable = Observable.just(student)
                .observeOn(Schedulers.io())
                .doOnNext(new Consumer<Student>() {
                    @Override
                    public void accept(Student student) throws Exception {
                        SQLiteDatabase sqLiteDatabase = new MySQLiteOpenHelper().getWritableDatabase();

                        //插入一行数据
                        ContentValues contentValues = new ContentValues();
                        contentValues.put("name", student.getName());
                        contentValues.put("sex", student.getSex());
                        contentValues.put("age", student.getAge());
                        sqLiteDatabase.insert("student", "", contentValues);
                        sqLiteDatabase.close();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<Student>() {
                            @Override
                            public void accept(Student student) throws Exception {

                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                throwable.printStackTrace();
                                ToastUtils.INSTANCE.showShort("存储失败", ToastUtils.INSTANCE.getDEFAULT_TOAST());
                            }
                        }, new Action() {
                            @Override
                            public void run() throws Exception {
                                readStudent();
                            }
                        });

    }

    private void readStudent() {
        Observable.create(new ObservableOnSubscribe<Student>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Student> emitter) throws Exception {
                SQLiteDatabase sqLiteDatabase = new MySQLiteOpenHelper().getReadableDatabase();
                Cursor cursor = null;
                try {
                    cursor = sqLiteDatabase.query("student",
                            null,
                            null,
                            null,
                            null,
                            null,
                            null
                    );
                    if (cursor.moveToFirst()) {
                        //存在数据，读取第一行
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        String sex = cursor.getString(cursor.getColumnIndex("sex"));
                        int age = cursor.getInt(cursor.getColumnIndex("age"));
                        if (!emitter.isDisposed()) {
                            emitter.onNext(new Student(name, sex, age));
                        }
                        if (!emitter.isDisposed()) {
                            emitter.onComplete();
                        }
                    } else {
                        if (!emitter.isDisposed()) {
                            emitter.onComplete();
                        }
                    }
                } catch (Exception e) {
                    if (!emitter.isDisposed()) {
                        emitter.onError(e);
                    }
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                    sqLiteDatabase.close();
                }

            }
        })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Student>() {
                    @Override
                    public void accept(Student student) throws Exception {
                        logView.addLog(student.getName());
                        logView.addLog(student.getSex());
                        logView.addLog(student.getAge());
                    }
                })
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        ToastUtils.INSTANCE.showShort("读取失败", ToastUtils.INSTANCE.getDEFAULT_TOAST());
                    }
                })
                .subscribe();
    }

    private static class MySQLiteOpenHelper extends SQLiteOpenHelper {

        public MySQLiteOpenHelper() {
            super(MyApplication.instance, "config", null, 1);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            //创建当前版本数据库
            //建表
            db.execSQL("create table student (name TEXT,sex TEXT,age INT);");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //数据库版本更新处理
        }
    }
}
